<template>
  <md-page
    :title="`${data.pageType === 'add' ? '新增' : '编辑'}收货地址`"
    isBtn
    :btnTextItems="data.btnTextItems"
    @btnClick="submit">
    <view class="page-container">
      <view class="form-wrap">
        <uni-forms ref="form" :modelValue="data.form" :rules="data.rules" label-position="top" label-width="100">
          <uni-forms-item label="姓名" name="name" required>
            <view class="form-item" style="padding: 0">
              <uni-easyinput v-model="data.form.name" placeholder="请输入" type="text" />
            </view>
          </uni-forms-item>
          <uni-forms-item label="手机号码" name="mobile" required>
            <view class="form-item" style="padding: 0">
              <uni-easyinput v-model="data.form.mobile" placeholder="请输入" type="number" />
            </view>
          </uni-forms-item>
          <uni-forms-item label="所在区域" name="district" required>
            <view class="form-item" style="padding: 0">
              <uni-data-picker
                v-model="data.form.district"
                :localdata="addressData"
                :map="{ text: 'areaName', value: 'areaName' }"
                @change="handleAreas" />
            </view>
          </uni-forms-item>
          <uni-forms-item label="详细地址" name="address" required>
            <view class="form-item" style="padding: 0">
              <uni-easyinput v-model="data.form.address" placeholder="请输入" type="text" />
            </view>
          </uni-forms-item>
          <label class="flex-l" @click="handleRadio">
            <radio color="#d92121" :checked="data.form.is_def" />
            <text class="m-left-8">设为默认值</text>
          </label>
        </uni-forms>
      </view>
    </view>
  </md-page>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
// 组件
import addressData from '@/pages/other/address/address-manage/address';
// 接口
import { userAddrAdd, userAddrEdit } from '@/api';
import type { UserAddr } from '@/api/data';
const data = reactive<any>({
  pageType: '',
  btnTextItems: [{ text: '提交', key: 'submit' }],
  form: {
    name: '',
    mobile: '',
    address: '',
    is_def: false,
    province: '',
    city: '',
    district: '',
  },
  rules: {
    name: {
      rules: [
        {
          required: true,
          errorMessage: '请输入姓名',
        },
      ],
    },
    mobile: {
      rules: [
        {
          required: true,
          errorMessage: '请输入手机号码',
        },
        // {
        //   required: true,
        //   pattern: /^1\d{10}$/,
        //   errorMessage: '请输入正确的手机号',
        // },
      ],
    },
    district: {
      rules: [
        {
          required: true,
          errorMessage: '请选择所在区域',
        },
      ],
    },
    address: {
      rules: [
        {
          required: true,
          errorMessage: '请输入详细地址',
        },
      ],
    },
  },
  configInfo: {},
});
const form = ref(null);
const areas = ref<Record<string, string>>({});

const handleRadio = () => {
  data.form.is_def = !data.form.is_def;
};

const handleAreas = (e: any) => {
  const { detail } = e;
  areas.value = {
    province: detail.value[0].value,
    city: detail.value[1].value,
  };
  // data.form.province = detail.value[0].value;
  // data.form.city = detail.value[1].value;
  // data.form.district = detail.value[2].value;
};

const submit = async () => {
  try {
    const res = await form.value?.validate();
    // console.log(res);
    if (data.pageType === 'add') {
      fetchUserAddrAdd({ ...res, ...areas.value, is_def: data.form.is_def ? 1 : 2 });
    } else {
      fetchUserAddrEdit({ ...res, ...areas.value, is_def: data.form.is_def ? 1 : 2, id: data.form?.id });
    }
  } catch (e) {
    //TODO handle the exception
    console.log('表单错误信息：', e);
  }
};

onLoad(options => {
  const configInfo = uni.getStorageSync('configInfo') ? JSON.parse(uni.getStorageSync('configInfo')) : '';
  if (configInfo) {
    data.configInfo = configInfo;
    data.btnTextItems = [
      {
        text: '提交',
        key: 'submit',
        color: data.configInfo.button_color1 || '#1CA4C0',
        textColor: data.configInfo.button_color1_text || '#ffffff',
      },
    ];
  }
  data.pageType = options?.type;
  if (options?.item) {
    const { is_def, ...item } = JSON.parse(options.item);
    data.form = {
      ...item,
      is_def: is_def == 1,
    };
  }
});

/**
 * 接口相关
 */
// 新增
const fetchUserAddrAdd = async (params: UserAddr.Add.Body) => {
  try {
    const res = await userAddrAdd(params);
    uni.showModal({
      title: '提示',
      content: res?.msg || '添加成功',
      showCancel: false,
      success: res => {
        if (res.confirm) {
          uni.navigateBack();
        }
      },
    });
  } catch (error) {}
};

// 编辑
const fetchUserAddrEdit = async (params: UserAddr.Add.Body & { id: number }) => {
  try {
    const res = await userAddrEdit(params);
    uni.showModal({
      title: '提示',
      content: res?.msg || '添加成功',
      showCancel: false,
      success: res => {
        if (res.confirm) {
          uni.navigateBack();
        }
      },
    });
  } catch (error) {}
};
</script>

<style lang="scss" scoped>
.page-container {
  width: 100%;
  display: flex;
  flex-direction: column;
  min-height: 100%;
  padding: 32rpx;
  box-sizing: border-box;
  background-color: #f5f5f5;
}
.form-item {
  background: white;
  border-radius: 10rpx;
  padding: 10rpx 0 10rpx 10px;
}
.radio-label {
  width: 100%;
  height: 124rpx;
  display: flex;
  align-items: center;
  padding: 0 32rpx;
  box-sizing: border-box;
  background-color: #f5f5f5;
}
</style>
